import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_nest_life/utils/TokenManager.dart';
import '../../api/user.dart';
import '../../utils/EventBus.dart';
import '../../utils/toast.dart';

class MinePage extends StatefulWidget {
  // const MinePage({Key? key}) : super(key: key);
  // 这里需要添加 super.key 才能正常编译，因为父类有一个构造函数需要传入 key 参数。如果父类没有构造函数，就不需要传入 key 参数。
  const MinePage(
      {super.key,
      required this.currentIndex,
      required this.updateCurrentIndex});
  final int currentIndex;
  final Function(int) updateCurrentIndex;
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // region 倒计时状态管理
  static const int _initialCountdownSeconds = 60;
  int _currentCountdownSeconds = _initialCountdownSeconds;
  Timer? _timer;
  bool _isCountdownRunning = false;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
  // endregion

  // region 页面数据
  final List<Map<String, String>> _menuItems = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  Map UserInfo = {
    "id": "",
    "nickName": "",
    "avatar": "",
  };

  @override
  void didUpdateWidget(MinePage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    // 点击“我的”时候触发change的时候，执行下面的代码
    if (widget.currentIndex == 1) {
      // PrompAction.showSuccess('提示：didUpdateWidget');
      getUserInfo();
    }
  }

  // 修改用户信息获取方法
  getUserInfo() async {
    final res = await getUserInfoAPI();
    if (mounted) {
      setState(() {
        UserInfo = res;
      });
    }
    print(res);
  }

// 修改头像构建逻辑
  Widget _buildAvatar() {
    return ClipRRect(
        borderRadius: BorderRadius.circular(50),
        child: UserInfo['avatar']?.isNotEmpty == true
            ? Image.network(
                UserInfo['avatar'],
                width: 50,
                height: 50,
                fit: BoxFit.cover,
              )
            : Image.asset(
                'assets/images/avatar.png',
                width: 50,
                height: 50,
              ));
  }

  // 退出登录
  _logout() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('温馨提示'),
            content: const Text('确定要退出吗？'),
            actions: [
              TextButton(
                onPressed: () {
                  // 关闭弹层
                  Navigator.pop(context);
                },
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  // 清除本地的token + refreshToken
                  tokenManager.deleteToken();
                  // 更新用户信息 -> 空
                  setState(() {
                    UserInfo = {'id': '', 'nickName': '', 'avatar': ''};
                  });
                  // 底部首页tab 切换 parentComp currentIndex 0 首页 / 1 我的
                  widget.updateCurrentIndex(0);
                },
                child: const Text('确认'),
              ),
            ],
          );
        });
  }

  @override
  void initState() {
    super.initState();
    // 订阅消息 LoginEvent
    registerLoginEvent();
    // 首次进入页面，主动加载用户信息
    getUserInfo();
  }

  registerLoginEvent() {
    eventBus.on<LoginEvent>().listen((event) {
      getUserInfo();
    });
  }

  final List<Map<String, String>> _tokenTestButtons = [
    {"title": "获取Token", "icon": "assets/images/1.png", "operation": "get"},
    {"title": "保存Token", "icon": "assets/images/2.png", "operation": "save"},
    {"title": "删除Token", "icon": "assets/images/3.png", "operation": "delete"}
  ];
  // endregion

  // region 主布局构建
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175), // 背景颜色
      appBar: _buildAppBar(), // 顶部AppBar
      body: ListView(
        children: [
          _buildProfileHeader(), // 个人信息头部
          _buildMenuSection(), // 菜单项
          _buildTokenTestSection(), // Token测试功能
          _buildCountdownSection(), // 倒计时功能
        ],
      ),
    );
  }

  AppBar _buildAppBar() {
    return AppBar(
      title: const Text('我的', style: TextStyle(color: Colors.white)),
      backgroundColor: Colors.transparent,
      centerTitle: true,
    );
  }
  // endregion

  // region 个人信息头部
  Widget _buildProfileHeader() {
    return Container(
      padding: const EdgeInsets.all(10),
      child: GestureDetector(
        onTap: () => Navigator.pushNamed(context, '/profile'),
        child: Row(
          children: [
            _buildAvatar(),
            const SizedBox(width: 10),
            _buildUserInfo(),
            const Spacer(),
            _buildProfileEditButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildUserInfo() {
    String nickName = UserInfo['nickName'] ?? '用户名';
    return Text(
      nickName,
      style: const TextStyle(fontSize: 16, color: Colors.white),
    );
  }

  Widget _buildProfileEditButton() {
    return GestureDetector(
      onTap: () => Navigator.pushNamed(context, '/profile',
          arguments: {'userInfo': UserInfo} // 添加参数传递
          ),
      child: const Row(
        children: [
          Text('去完善信息', style: TextStyle(color: Colors.white)),
          Icon(Icons.arrow_forward_ios, color: Colors.white, size: 13),
        ],
      ),
    );
  }
  // endregion

  // region 菜单项构建
  Widget _buildMenuSection() {
    return _buildSectionContainer(
      child: Column(
        children: _menuItems.map(_buildMenuItem).toList(),
      ),
    );
  }

  Widget _buildMenuItem(Map<String, String> item) {
    return SizedBox(
      height: 50,
      child: Row(
        children: [
          Image.asset(item['icon']!, width: 20, height: 20),
          const SizedBox(width: 10),
          Text(item['title']!, style: const TextStyle(fontSize: 16)),
          const Spacer(),
          const Icon(Icons.arrow_forward_ios, size: 12, color: Colors.grey),
        ],
      ),
    );
  }
  // endregion

  // region Token测试功能
  Widget _buildTokenTestSection() {
    return _buildSectionContainer(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: _tokenTestButtons.map(_buildTokenButton).toList(),
      ),
    );
  }

  Widget _buildTokenButton(Map<String, String> button) {
    return Expanded(
      child: GestureDetector(
        onTap: () => _handleTokenOperation(button['operation']!),
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 5),
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: _buildButtonDecoration(Colors.blue[50]!),
          child: Column(
            children: [
              Image.asset(button['icon']!, width: 24, height: 24),
              const SizedBox(height: 6),
              Text(
                button['title']!,
                style: const TextStyle(
                  fontSize: 13,
                  color: Colors.blue,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  // endregion

  // region 倒计时功能
  Widget _buildCountdownSection() {
    return _buildSectionContainer(
      child: Column(
        children: [
          _buildCountdownDisplay(), // 倒计时显示
          const SizedBox(height: 15),
          _buildCountdownControls(), // 倒计时控制按钮
        ],
      ),
    );
  }

  Widget _buildCountdownDisplay() {
    return Text(
      '倒计时: $_currentCountdownSeconds 秒',
      style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
    );
  }

  Widget _buildCountdownControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildCountdownButton(
          text: '开始倒计时',
          color: _isCountdownRunning ? Colors.grey : Colors.blue,
          onTap: _isCountdownRunning ? null : _startCountdown,
        ),
        _buildCountdownButton(
          text: '停止倒计时',
          color: _isCountdownRunning ? Colors.red : Colors.grey,
          onTap: _isCountdownRunning ? _stopCountdown : null,
        ),
      ],
    );
  }

  /// 构建倒计时按钮组件
  /// [text] - 按钮显示的文本
  /// [color] - 按钮的颜色
  /// [onTap] - 按钮点击回调函数
  Widget _buildCountdownButton({
    required String text, // 按钮文本 （required-必填）
    required Color color, // 按钮颜色
    required VoidCallback? onTap, // 点击回调（回调函数类型）
  }) {
    return Expanded(
      // 使用Expanded让按钮填充可用空间
      child: GestureDetector(
        // 添加点击手势
        onTap: onTap,
        child: Container(
          // 按钮容器
          margin: const EdgeInsets.symmetric(horizontal: 5), // 水平方向边距
          padding: const EdgeInsets.symmetric(vertical: 12), // 垂直方向内边距
          decoration:
              _buildButtonDecoration(color.withOpacity(0.2)), // 设置按钮装饰样式
          alignment: Alignment.center, // 居中对齐
          child: Text(
            // 按钮文本
            text,
            style: TextStyle(
              fontSize: 13, // 字体大小
              color: color, // 文本颜色
              fontWeight: FontWeight.w500, // 字体粗细
            ),
          ),
        ),
      ),
    );
  }
  // endregion

  // region 通用工具方法
  Widget _buildSectionContainer({required Widget child}) {
    return Container(
      padding: const EdgeInsets.all(15),
      margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: child,
    );
  }

  BoxDecoration _buildButtonDecoration(Color color) {
    return BoxDecoration(
      color: color,
      borderRadius: BorderRadius.circular(8),
    );
  }

  Future<void> _handleTokenOperation(String operation) async {
    const testToken = 'V8RE4839HH4FU';
    switch (operation) {
      case 'get':
        final token = tokenManager.getToken();
        PromptAction.showInfo(token.isNotEmpty ? token : '无存储Token');
        break;
      case 'save':
        tokenManager.saveToken(testToken);
        PromptAction.showSuccess('Token保存成功');
        break;
      case 'delete':
        await tokenManager.deleteToken();
        PromptAction.showError('Token删除成功');
        break;
    }
  }
  // endregion

  // region 倒计时逻辑
  void _startCountdown() {
    if (_isCountdownRunning) return;

    setState(() {
      _currentCountdownSeconds = _initialCountdownSeconds;
      _isCountdownRunning = true;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }
      setState(() {
        if (_currentCountdownSeconds > 0) {
          _currentCountdownSeconds--;
        } else {
          _stopCountdown();
        }
      });
    });
  }

  void _stopCountdown() {
    _timer?.cancel();
    if (mounted) {
      setState(() {
        _isCountdownRunning = false;
        _currentCountdownSeconds = _initialCountdownSeconds;
      });
    }
  }
  // endregion
}
